//
//  HubuFirstViewController.m
//  iHubu2
//
//  Created by hanshui on 12-10-31.
//  Copyright (c) 2012年 hanshui. All rights reserved.
//

#import "HubuFirstViewController.h"
#import "HubuQueryViewController.h"
#import "HubuNewsViewController.h"
#import "HubuAppDelegate.h"

#import "AdViewController.h"

#import "ASIHTTPRequest.h"
#import "OPACConstant.h"
#import "OPACBookObjects.h"
#import "DBUtil.h"
#import "RegexKitLite.h"

static NSUInteger kNumberOfPages = 3;

@interface HubuFirstViewController ()

@end

@implementation HubuFirstViewController

@synthesize adScrollView, adPageControl, adViewControllers;
@synthesize bookSearchBar;
@synthesize noticeButton, newsButton, newsTableView;

- (void)dealloc
{
    [adScrollView release];
    [adPageControl release];
    [adViewControllers release];
    
    [bookSearchBar release];
    [noticeButton release];
    [newsButton release];
    [newsTableView release];
    
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)getNewsData {
    if(noticesData == nil) {
        noticesData = [[NSMutableArray alloc] initWithCapacity:5];
    }
    if(newsData == nil) {
        newsData = [[NSMutableArray alloc] initWithCapacity:5];
    }
    //新闻数据
    DBUtil *db = [[DBUtil alloc] init];
    [db openDB];
    [db getAllNews:noticesData news:newsData];
    [db closeDB];
    [db release];
    
    [self.newsTableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [[[self.bookSearchBar subviews] objectAtIndex:0] removeFromSuperview];
    
    [self getNewsData];
    
    //上半部分的广告导航
    //广告 － 开始
	NSMutableArray *controllers = [[NSMutableArray alloc] init];
    for (unsigned i = 0; i < kNumberOfPages; i++) {
        [controllers addObject:[NSNull null]];
    }
    self.adViewControllers = controllers;
    [controllers release];
	
    // a page is the width of the scroll view
    adScrollView.pagingEnabled = YES;
    adScrollView.contentSize = CGSizeMake(adScrollView.frame.size.width * kNumberOfPages, adScrollView.frame.size.height);
    adScrollView.showsHorizontalScrollIndicator = NO;
    adScrollView.showsVerticalScrollIndicator = NO;
    adScrollView.scrollsToTop = NO;
    adScrollView.delegate = self;
	
    adPageControl.numberOfPages = kNumberOfPages;
    adPageControl.currentPage = 0;
    [adPageControl setBounds:CGRectMake(0, 0, 16 * (kNumberOfPages - 1) + 16, 16)];// pageControl上的圆点间距基本在16左右
    [adPageControl.layer setCornerRadius:8];
    [adPageControl setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.2]];
	
    // pages are created on demand
    // load the visible page
    // load the page on either side to avoid flashes when the user starts scrolling
    [self adLoadScrollViewWithPage:0];
    [self adLoadScrollViewWithPage:1];
    //广告 － 结束
    
    //获取最新的新闻
    NSURL *url = [NSURL URLWithString:NEWS_CATEGORY];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    
    [request setDidFinishSelector:@selector(requestCompleted:)];
    [request setDidFailSelector:@selector(requestError:)];
    
    [request setDelegate:self];
    [request startAsynchronous];
}

//广告方法 － 开始
#pragma mark -
#pragma mark scroll ad for finger spinning
- (void)adLoadScrollViewWithPage:(int)page {
    if (page < 0) return;
    if (page >= kNumberOfPages) return;
	
    // replace the placeholder if necessary
    AdViewController *controller = [adViewControllers objectAtIndex:page];
    if ((NSNull *)controller == [NSNull null]) {
        controller = [[AdViewController alloc] initWithPageNumber:page];
        [adViewControllers replaceObjectAtIndex:page withObject:controller];
        [controller release];
    }
	
    // add the controller's view to the scroll view
    if (nil == controller.view.superview) {
        CGRect frame = adScrollView.frame;
        frame.origin.x = frame.size.width * page;
        frame.origin.y = 0;
        controller.view.frame = frame;
        [adScrollView addSubview:controller.view];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    // We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
    // which a scroll event generated from the user hitting the page control triggers updates from
    // the delegate method. We use a boolean to disable the delegate logic when the page control is used.
    if (adPageControlUsed) {
        // do nothing - the scroll was initiated from the page control, not the user dragging
        return;
    }
	
    // Switch the indicator when more than 50% of the previous/next page is visible
    CGFloat pageWidth = adScrollView.frame.size.width;
    int page = floor((adScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    adPageControl.currentPage = page;
	
    // load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
    [self adLoadScrollViewWithPage:page - 1];
    [self adLoadScrollViewWithPage:page];
    [self adLoadScrollViewWithPage:page + 1];
	
    // A possible optimization would be to unload the views+controllers which are no longer visible
}

// At the begin of scroll dragging, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    adPageControlUsed = NO;
}

// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
	adPageControlUsed = NO;
}

- (IBAction)adChangePage:(id)sender {
    int page = adPageControl.currentPage;
	
    // load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
    [self adLoadScrollViewWithPage:page - 1];
    [self adLoadScrollViewWithPage:page];
    [self adLoadScrollViewWithPage:page + 1];
    
	// update the scroll view to the appropriate page
    CGRect frame = adScrollView.frame;
    frame.origin.x = frame.size.width * page;
    frame.origin.y = 0;
    [adScrollView scrollRectToVisible:frame animated:YES];
    
	// Set the boolean used when scrolls originate from the UIPageControl. See scrollViewDidScroll: above.
    adPageControlUsed = YES;
}
//广告方法 － 结束

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(IBAction)showClick:(id)sender {
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Show" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//    [alert show];
//    [alert release];
    HubuQueryViewController *hubuQueryViewController = [[[HubuQueryViewController alloc] initWithNibName:@"HubuQueryViewController" bundle:nil] autorelease];
    
    //NSDate *object = _objects[indexPath.row];
    //self.detailViewController.detailItem = object;
    HubuAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    [delegate.navigationController pushViewController:hubuQueryViewController animated:YES];
}


-(IBAction)hiddenKeyboard:(id)sender {
    bookSearchBar.text = @"";
    [bookSearchBar resignFirstResponder];
}

- (void)requestCompleted:(ASIHTTPRequest *)request
{
//    NSMutableData *webData = [[NSMutableData alloc] init];
//    [webData appendData:[request responseData]];
//    NSString *theXML = [[NSString alloc] initWithBytes:[webData mutableBytes]
//												length:[webData length]
//											  encoding:NSASCIIStringEncoding];
//        NSLog(@"webData:%@", theXML);
    //    NSLog(@"webData2:%@", [OPACViewController replaceUnicode:theXML]);
    //    NSString *responseString = [[request responseString] dataUsingEncoding:NSUTF8StringEncoding];
    //    NSLog(@"responseString:%@", responseString);
    //[self clearHTMLData2Array:theXML];
    
    NSString *responseString = [request responseString];
    //NSLog(@"news:%@", responseString);
    [self clearHTMLData2Array:responseString];
}

- (void)requestError:(ASIHTTPRequest *)request {
    NSError *error = [request error];
    NSLog(@"error:%@", error);
    /*
    UIAlertView *loginAlertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                             message:@"数据错误，如多次出现请联系管理员。"
                                                            delegate:self
                                                   cancelButtonTitle:@"关闭"
                                                   otherButtonTitles:nil, nil];
    [loginAlertView show];
    [loginAlertView release];
     */
}


- (void) clearHTMLData2Array:(NSString *) sourceCode {
    NSMutableArray *newsListArray = [[NSMutableArray alloc] initWithCapacity:5];

    
    //获取每一本图书信息
    NSRange listNewsBegin = [sourceCode rangeOfString:NEWS_ITEM_TYPE_BEGIN];
    int i = 0;
    while ((listNewsBegin.location != NSNotFound)) {
        News *newsItem = [[News alloc] init];
        NSRange listNewsEnd = [sourceCode rangeOfString:NEWS_ITEM_ID_BEGIN options:nil range:NSMakeRange(listNewsBegin.location, sourceCode.length - listNewsBegin.location)];
        if(listNewsEnd.location != NSNotFound) {
            newsItem.newsType = [sourceCode substringWithRange:NSMakeRange(listNewsBegin.location + listNewsBegin.length, listNewsEnd.location - (listNewsBegin.location + listNewsBegin.length))];
        } else {
            break;
        }
        
        NSRange listIdEnd = [sourceCode rangeOfString:NEWS_ITEM_ID_END options:nil range:NSMakeRange(listNewsEnd.location, sourceCode.length - listNewsEnd.location)];
        if(listIdEnd.location != NSNotFound) {
            newsItem.newsId = [sourceCode substringWithRange:NSMakeRange(listNewsEnd.location + listNewsEnd.length, listIdEnd.location - (listNewsEnd.location + listNewsEnd.length))];
        } else {
            break;
        }
        
        NSRange listDateEnd;
        NSRange listTitleBegin = [sourceCode rangeOfString:NEWS_ITEM_TITLE_BEGIN options:nil range:NSMakeRange(listIdEnd.location, sourceCode.length - listIdEnd.location)];
        if(listIdEnd.location != NSNotFound) {
            NSRange listTitleEnd = [sourceCode rangeOfString:NEWS_ITEM_DATE_BEGIN options:nil range:NSMakeRange(listTitleBegin.location, sourceCode.length - listTitleBegin.location)];
            if(listIdEnd.location != NSNotFound) {
                newsItem.newsTitle = [sourceCode substringWithRange:NSMakeRange(listTitleBegin.location + listTitleBegin.length, listTitleEnd.location - (listTitleBegin.location + listTitleBegin.length))];
            } else {
                break;
            }
            
            listDateEnd = [sourceCode rangeOfString:NEWS_ITEM_DATE_END options:nil range:NSMakeRange(listTitleEnd.location, sourceCode.length - listTitleEnd.location)];
            if(listDateEnd.location != NSNotFound) {
                newsItem.newsDate = [sourceCode substringWithRange:NSMakeRange(listTitleEnd.location + listTitleEnd.length, listDateEnd.location - (listTitleEnd.location + listTitleEnd.length))];
            } else {
                break;
            }
        } else {
            break;
        }
        
        //[newsItem toString];
        
        [newsListArray addObject:newsItem];
        [newsItem release];
        
        listNewsBegin = [sourceCode rangeOfString:NEWS_ITEM_TYPE_BEGIN options:nil range:NSMakeRange(listDateEnd.location, sourceCode.length - listDateEnd.location)];
    }
    
    DBUtil *db = [[DBUtil alloc] init];
    [db openDB];
    BOOL returnStatus = [db insertOrUpdate:newsListArray];
    [db closeDB];
    [db release];
    
    if(returnStatus) {
        [self getNewsData];
    }
    
    [newsListArray release];
}

#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(noticeOrNews == 0) {
        return [noticesData count];
    } else {
        return [newsData count];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellTableIdentifier = @"CellTableIdentifier";
     
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
    CellTableIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier: CellTableIdentifier] autorelease];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:18];
    cell.textLabel.textColor = [UIColor colorWithRed:0.2 green:0.4 blue:0.4 alpha:1.0];
    if(noticeOrNews == 0) {
        News *newItem = [noticesData objectAtIndex:[indexPath row]];
        cell.textLabel.text = [newItem.newsTitle stringByReplacingOccurrencesOfRegex:@"&#[0-9]{4};" withString:@" "];
    }else {
        News *newItem = [newsData objectAtIndex:[indexPath row]];
        cell.textLabel.text = [newItem.newsTitle stringByReplacingOccurrencesOfRegex:@"&#[0-9]{4};" withString:@" "];
    }
    
    return cell;
}

/*
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(tableView == mainTableView){
        return 86;
    }else{
        return 44;
    }
}
*/

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HubuNewsViewController *hubuNewsViewController = [[HubuNewsViewController alloc] initWithNibName:@"HubuNewsViewController" bundle:nil];
    if(noticeOrNews == 0) {
        News *noticeItem = [noticesData objectAtIndex:[indexPath row]];
        [hubuNewsViewController showNewsInfo:noticeItem.newsId newTitle:noticeItem.newsTitle];
    } else {
        News *newsItem = [newsData objectAtIndex:[indexPath row]];
        [hubuNewsViewController showNewsInfo:newsItem.newsId newTitle:newsItem.newsTitle];
    }
    
    //NSDate *object = _objects[indexPath.row];
    //self.detailViewController.detailItem = object;
    HubuAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    [delegate.navigationController pushViewController:hubuNewsViewController animated:YES];
    [hubuNewsViewController release];
}

-(IBAction)noticesAndNewsClick:(id)sender {
    int tag = ((UIButton *)sender).tag;
    noticeOrNews = tag;
    if(noticeOrNews == 0) {
        [noticeButton setBackgroundImage:[UIImage imageNamed:@"ihubei_category_title_bg.png"] forState:UIControlStateNormal];
        [newsButton setBackgroundImage:nil forState:UIControlStateNormal];
    } else {
        [newsButton setBackgroundImage:[UIImage imageNamed:@"ihubei_category_title_bg.png"] forState:UIControlStateNormal];
        [noticeButton setBackgroundImage:nil forState:UIControlStateNormal];
    }
    [self.newsTableView reloadData];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    HubuQueryViewController *hubuQueryViewController = [[HubuQueryViewController alloc] initWithNibName:@"HubuQueryViewController" bundle:nil];
    [hubuQueryViewController showSearchListInfo:searchBar.text];
    
    HubuAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    [delegate.navigationController pushViewController:hubuQueryViewController animated:YES];
    [hubuQueryViewController release];
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searchBar.text = @"";
    [searchBar resignFirstResponder];
}
@end
